class CommentsController < ApplicationController
  before_filter :require_login,         :only => [:create,  :edit,    :new,     :update, :destroy]
  before_filter :find_comment,          :only => [:show,    :edit,    :update,  :destroy]
  before_filter :require_authorization, :only => [:destroy, :update,  :edit]

  def index
    @comments = Comment.find(:all, :order => 'created_at DESC')
  end

  def show
  end

  def new
    @comment = comment.new
  end

  def create
    @comment = Comment.new(params[:comment])
    @comment.user = current_user
    @comment.save!
    flash[:update] = 'The comment has been added'
    redirect_to :back
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    redirect_to :back
  end

  def edit
  end

  def update
    @comment.update_attributes!(params[:comment])
    flash[:update] = 'The comment has been updated.'
    redirect_to :back
  rescue ActiveRecord::RecordInvalid
    flash[:error] = "Oops, that didn't work, see below."
    redirect_to :back
  end

  def destroy
    @comment.destroy
    flash[:update] = 'The comment has been deleted.'
    redirect_back_or_default('/')   
  end

protected
  def require_authorization
    @comment.authorized_to_modify?(current_user)
  end
  def require_login
    unless logged_in?
      flash[:error] = 'You must be logged in to do that'
      redirect_to login_url
    end
  end
  def find_comment
    @comment = Comment.find params[:id]
  end
end
